﻿using System;
using System.Web;
using DMS.Business.Authority;
using DMS.Business.Authority.Impl;
using DMS.Business.Utility;

namespace DMS.Business.EventHanlder
{
    public class AuthHandler : IHttpModule
    {

        #region IHttpModule Members

        private const string LoginPage = "/login.aspx";
        private const string SignoutPage = "/signout.aspx";
        private const string ErrorPage = "/error.aspx";
        private const string Randomimage = "/common/services/getrandomimage.aspx";
        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.Error += new System.EventHandler(context_Error);
            //context.BeginRequest += (new System.EventHandler(this.Application_BeginRequest));
            context.AuthenticateRequest += (new System.EventHandler(this.ApplicationAuthenticateRequest));
        }

        private void context_Error(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            Exception lastException = context.Server.GetLastError();

            LogHelper.LogException(lastException);
        }

        private void ApplicationBeginRequest(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            LogHelper.LogAction2("Application_BeginRequest", "请求开始！");
        }

         /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void ApplicationAuthenticateRequest(Object source, EventArgs e)
         {
            var application = (HttpApplication)source;
            HttpContext context = application.Context;
            string url = context.Request.Path.ToLower();//得到用户请求的虚拟路径
            
            if (url.IndexOf(".aspx") >= 0 //只判断aspx页面
                && (url != LoginPage && url != SignoutPage 
                && url != ErrorPage && url != Randomimage))//排除登录、注销、错误、随机码页面
            {
                IAuthorityFacade authorityFacade = new AuthorityFacadeImpl();
                string hostInfo = "客户端IP：" + context.Request.UserHostAddress;

                if (!context.Request.IsAuthenticated)
                {
                    //AuthCheckFailured(context, url, hostInfo);
                }
                else
                {
                    if (authorityFacade.CheckUrlPermission(SystemContext.Current.LoginAuthUser.ID.ToString(), url))
                    {
                        AuthCheckSucceed(url, hostInfo);
                    }else
                    {
                        AuthCheckFailured(context, url, hostInfo);
                    }
                }
            }
         }

        /// <summary>
        /// 验证成功处理
        /// </summary>
        /// <param name="url"></param>
        /// <param name="hostInfo"></param>
        private void AuthCheckSucceed(string url, string hostInfo)
        {
            //LogHelper.LogAction("权限验证", "请求页面：" + url + "，已授权！" + hostInfo);
        }

        /// <summary>
        /// 验证失败处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="url"></param>
        /// <param name="hostInfo"></param>
        private void AuthCheckFailured(HttpContext context,string url, string hostInfo)
        {
            LogHelper.LogAction2("权限验证", "请求页面：" + url + "，未授权！" + hostInfo);
            context.Response.Redirect(ErrorPage+ "?info=" + "请求页面：" + url + "，未授权！" + hostInfo);
        }

        #endregion
    }
}
